package com.rdc.dictionary.vocabulary;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.rdc.dictionary.R;
import com.rdc.dictionary.adapter.WordsAdapter;
import com.rdc.dictionary.application.App;
import com.rdc.dictionary.bean.Word;
import com.rdc.dictionary.util.FileUtil;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;

/**
* @file 文件名
* @author Soul Mate
* @brief 生词本 活动
*/
public class VocabularyActivity extends AppCompatActivity
{

	//排序方式的控件
	private Button SortTime;
	private Button SortLetter;

	//记录排序的方式
	Boolean isTime;


	@Override protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vocabulary);

		//初始化控件
		SortTime = findViewById(R.id.bt_time);
		SortLetter = findViewById(R.id.bt_letter);

		SortTime.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				//默认按添加时间读取数据库中的生词表
				isTime = true;

				//从数据库获取
				List<Word> newWord = DataSupport.findAll(Word.class);
				initRecyclerView(newWord);
			}
		});


		SortLetter.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				//按字母排序读取数据库中的生词表
				isTime = false;

				//从数据库获取
				List<Word> newWord = DataSupport.order("word asc").find(Word.class);
				initRecyclerView(newWord);
			}
		});

	}


	//RecyclerView的操作
	public void initRecyclerView(List<Word> newWord)
	{
		RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		recyclerView.setLayoutManager(layoutManager);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

		//new adapter 同时设置删除
		WordsAdapter adapter = new WordsAdapter(newWord, new WordsAdapter.NewWordOnItemClickListener()
		{
			@Override public void onClickDelete(int position)
			{
				Word w = newWord.get(position);

				//删除数据库中数据
				DataSupport.deleteAll(Word.class, "word = ?" , w.getWord());

				//文件处理类的单例
				FileUtil fileUtil = FileUtil.getInstance();

				//获取要删除的路径
				String path = fileUtil.getPath(w.getWord());
				File file = new File(path);
				//删除相关文件（mp3）
				fileUtil.deleteFile(file);

				//重新加载生词本
				reload();


			}
		});
		recyclerView.setAdapter(adapter);
	}

	/**
	* 重新显示生词本（根据某种方式）
	*/
	public void reload()
	{
		List<Word> newWord;
		if(isTime)
		{
			//默认时间排序
			newWord = DataSupport.findAll(Word.class);

		}else
		{
			//字母排序
			newWord = DataSupport.order("word asc").find(Word.class);

		}
		initRecyclerView(newWord);

	}


}